package com.muk.webframework.framework.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.muk.webframework.framework.log.LoggerFile;
import com.muk.webframework.framework.util.MapUtil;

public abstract class BaseController extends HttpServlet {
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		LoggerFile.log("*********** Start request " + request.getPathInfo());
		LoggerFile.log("*********** Start request " + request.getRequestURL());
		this.request = request;
		this.response = response;
		this.session = request.getSession();
		System.out.println("parameter list : "
				+ MapUtil.ToStringMap(this.request.getParameterMap()));
		String pathInfo = request.getPathInfo();
		LoggerFile.log(pathInfo);		
		String methodName = pathInfo.replaceAll("/", "");//this.request.getParameter("method");
		try {
			Method method = this.getClass().getMethod(methodName,new Class[] {});
			method.invoke(this, null);
		} catch (NoSuchMethodException | SecurityException |
				IllegalAccessException | IllegalArgumentException |
				InvocationTargetException e) {
			e.printStackTrace();
		}

		LoggerFile.log("*********** End request " + request.getContextPath());
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
		// processRequest();
	}

	protected void dispatcher(String name) throws ServletException, IOException{
		ServletContext context = getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher(name);
		dispatcher.forward(request, response);
	}

}
